package cn.coisini.utils;

import io.netty.util.internal.ThreadLocalRandom;
import lombok.Getter;

import java.awt.*;
import java.awt.image.BufferedImage;

/**
 * @author xiangshaw
 * Description: 验证码工具类
 */
@Getter
public class CaptchaUtil {

    private CaptchaUtil() {
        throw new IllegalStateException("Utility class");
    }

    private static final int WIDTH = 160;
    private static final int HEIGHT = 40;
    private static final int CODE_COUNT = 4;
    private static final int FONT_HEIGHT = 30;
    private static final char[] CODE_SEQUENCE = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};


    public static Captcha generateCaptcha() {
        BufferedImage buffImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();

        // 创建一个随机数生成器类
        ThreadLocalRandom random = ThreadLocalRandom.current();

        // 将图像填充为白色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 创建字体，字体的大小应该根据图片的高度来定
        Font font = new Font("Fixedsys", Font.BOLD, FONT_HEIGHT);
        g.setFont(font);

        // 画边框
        g.setColor(Color.BLACK);
        g.drawRect(0, 0, WIDTH - 1, HEIGHT - 1);

        // 随机产生干扰线，使图像中的认证码不易被其它程序探测到
        g.setColor(Color.BLACK);
        for (int i = 0; i < 30; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            g.drawLine(x, y, x + xl, y + yl);
        }

        // randomCode用于保存随机产生的验证码，以便用户登录后进行验证
        StringBuilder randomCode = new StringBuilder();
        int red;
        int green;
        int blue;

        // 随机产生验证码字符
        for (int i = 0; i < CODE_COUNT; i++) {
            // 得到随机产生的验证码字符
            String code = String.valueOf(CODE_SEQUENCE[random.nextInt(CODE_SEQUENCE.length)]);

            // 产生随机的颜色分量来构造颜色值，这样输出的每位数字的颜色值都将不同
            red = random.nextInt(255);
            green = random.nextInt(255);
            blue = random.nextInt(255);

            // 用随机产生的颜色将验证码绘制到图像中
            g.setColor(new Color(red, green, blue));
            g.drawString(code, (i + 1) * 30, 30);

            // 将产生的四个随机数组合在一起
            randomCode.append(code);
        }

        return new Captcha(buffImg, randomCode.toString());
    }


    public record Captcha(BufferedImage image, String code) {
    }
}
